import {login} from '@/api/sys'
import {setItem, getItem, removeAllItem} from '@/utils/storage'
import {TOKEN, USERINFO, USERID, USERNAME, ADMIN} from '@/constant'
// import router from '@/router'
import router, {resetRouter} from '@/router'
import {ElNotification} from 'element-plus'

export default {
    namespaced: true,
    state: () => ({
        token: getItem(TOKEN) || '',
        userInfo: getItem(USERINFO) || '',
        userId: getItem(USERID) || '',
        userName: getItem(USERNAME) || '',
        admin: getItem(ADMIN) || ''
    }),
    mutations: {
        setToken(state, token) {
            state.token = token
            setItem(TOKEN, token)
        },
        setUserInfo(state, info) {
            state.userInfo = info
            setItem(USERINFO, info)
        },
        setUserId(state, id) {
            state.userId = id
            setItem(USERID, id)
        },
        setUserName(state, name) {
            state.userName = name
            setItem(USERNAME, name)
        },
        setUserAdmin(state, admin) {
            state.admin = admin
            setItem(ADMIN, admin)
        }
    },
    actions: {
        logout() {
            resetRouter()
            this.commit('user/setToken', '')
            this.commit('user/setUserInfo', '')
            this.commit('user/setUserId', '')
            this.commit('user/setUserName', '')
            this.commit('user/setUserAdmin', '')
            removeAllItem()

            ElNotification({
                title: 'Success',
                message: '已登出',
                type: 'success',
                duration: 2000,
                onClose: () => {
                    // 在组件中调用 window.location.reload() 来刷新当前页面
                    window.location.reload()
                }
            })
        }
    }
}
